package top.hkyzf.event;

import com.mojang.logging.LogUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ClientChatEvent;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.slf4j.Logger;
import top.hkyzf.util.ClientConfig;
import top.hkyzf.util.Utils;

import java.util.UUID;

/**
 * description: 聊天框相关事件
 * @author zhufeng
 * @date 2022/8/5 13:57
 * @version V1.0
 */
@Mod.EventBusSubscriber(value = Dist.CLIENT)
public class ChatEvents {
    /**
     * 获取一个 slf4j 日志记录器
     */
    private static final Logger LOGGER = LogUtils.getLogger();
    /**
     * 聊天框快捷回家字符
     */
    private static final Character GO_HOME = 't';
    /**
     * 快捷回家字符串前缀
     */
    private static final String GO_HOME_PRE = "tp";

    /**
     * 登录提示符
     */
    private static final String LOGIN_TIPS = "/login";

    /**
     * 客户端聊天框消息发送事件
     * @param event 发送消息的事件
     */
    @SubscribeEvent
    public static void onChat(ClientChatEvent event) {
        LOGGER.info("客户端聊天框事件消息内容：{} - {}", event.getMessage(), event.getOriginalMessage());
    }

    /**
     * 客户端聊天框信息接收事件
     * @param event 接收到消息的事件
     */
    @SubscribeEvent
    public static void onChatReceived(ClientChatReceivedEvent event) {
        Player player = Minecraft.getInstance().player;
        String msg = event.getMessage().getString();
        if (player != null) {
            UUID playerId = player.getUUID();
            UUID senderId = event.getSenderUUID();
            LOGGER.info("玩家的UUID：{}", playerId);
            LOGGER.info("事件发送者的UUID：{}", senderId);
            LOGGER.info("客户端接收到消息：{}", msg);
            // customName:无 - displayName:餏HKY_ZF - name:HKY_ZF
            // 自动登录，只有 HKY_ZF 可以自动登录
            if (msg.contains(LOGIN_TIPS) && ClientConfig.DEFAULT_USERNAME.get().equals(player.getName().getString())) {
                Utils.sendCommand("/login " + ClientConfig.DEFAULT_PASSWORD.get());
            }
            // 判断是否是自己发送的消息
            if (playerId.equals(senderId)) {
                // 聊天框输入 t 直接回默认的家
                if (msg.lastIndexOf(GO_HOME) == msg.length() - 1) {
                    Utils.sendCommand("/home " + ClientConfig.DEFAULT_HOME.get());
                    // 聊天框输入 tpa 直接回名字叫 a 的家，输入 tp 回名字叫 Home 的家
                } else if (msg.contains(GO_HOME_PRE)) {
                    int index = msg.indexOf(GO_HOME_PRE) + GO_HOME_PRE.length();
                    String home = msg.substring(index);
                    if (home.length() == 0) {
                        home = ClientConfig.DEFAULT_HOME.get();
                    }
                    LOGGER.info("本次传送的家的名称是：{}", home);
                    Utils.sendCommand("/home " + home);
                }
            }
        }
    }
}
